#include "GameState.h"
#include "Constants.h"
#include "support/user_default/CCUserDefault.h"
USING_NS_CC;
GameState* GameState::instance = 0;

void GameState::init(CCLayer *layer) {

	owner = layer;

	scores = 0;
	lifes = START_LIFE;

	eggArray = new CCArray();

	CCSize visible = CCDirector::sharedDirector()->getVisibleSize();

	CCSprite* egg = CCSprite::create("egg.png");
	CCSize eggSize = egg->getContentSize();

	float deltaX = eggSize.width*1.2;
	float deltaY = eggSize.height;

	float currentX = eggSize.width*0.7;
	float currentY = visible.height-eggSize.height;

	for (int i = 0; i< lifes -1 ;  i++){
		CCSprite* egg = CCSprite::create("egg.png");

		egg->setPosition(ccp(currentX, currentY));

		eggArray->addObject(egg);

		owner->addChild(egg, indexEgg);

		currentX +=deltaX;
	}

	float scorePosX = visible.width/2;
	float scorePosY = currentY;

	scoreLabel = CCLabelTTF::create("0", gameOverFont, fontSize);
	scoreLabel->setPosition(ccp(scorePosX, scorePosY));


	scoreLabel->setColor(COLOR_SCORE_IN_GAME);

	owner->addChild(scoreLabel,indexText);

}

GameState* GameState::getInstance() {
	if (!instance) {
		instance = new GameState();
	}

	return instance;
}

void GameState::increaseScores(int score) {
	scores+= score;
	char* s = new char[4];

	sprintf(s, "%d", scores);
	scoreLabel->setString(s);
	delete[] s;
}

void GameState::increaseScores() {
	increaseScores(1);

}
void GameState::decreaseLifes() {
	lifes--;
	CCObject *egg = eggArray->lastObject();
	owner->removeChild((CCNode*)egg);
	eggArray->removeObject(egg);
}

int GameState::getScores() {
	return scores;
}

int GameState::getlifes() {
	return lifes;
}

void GameState::saveBestScore() {
	CCUserDefault *def = CCUserDefault::sharedUserDefault();
	def->setIntegerForKey(kBestScore, scores);
	def->flush();
}
int GameState::getBestScore() {
	return CCUserDefault::sharedUserDefault()->getIntegerForKey(kBestScore);
}

bool GameState::isBestScore() {
	return scores > CCUserDefault::sharedUserDefault()->getIntegerForKey(kBestScore) ? true : false;
}
